#!/bin/bash

set -o errexit
set -o xtrace

test_dir=$(realpath $(dirname $0))
. ${test_dir}/../functions
cluster="monitoring"

deploy_cert_manager
create_namespace $namespace
deploy_operator

desc 'install PMM Server'
platform=kubernetes

helm del --purge monitoring || :
helm repo remove stable || :
helm repo add stable https://charts.helm.sh/stable
if [[ -n "${OPENSHIFT}" ]]; then
    platform=openshift
    oc adm policy add-scc-to-user privileged -z percona-server-mongodb-operator
    oc patch role/percona-server-mongodb-operator --type json -p='[{"op":"add","path": "/rules/-","value":{"apiGroups":["security.openshift.io"],"resources":["securitycontextconstraints"],"verbs":["use"],"resourceNames":["privileged"]}}]'
    retry 10 60 helm install monitoring --set platform=$platform --set sa=percona-server-mongodb-operator --set supresshttp2=false https://percona-charts.storage.googleapis.com/pmm-server-2.12.3.tgz
else
    retry 10 60 helm install monitoring --set platform=$platform https://percona-charts.storage.googleapis.com/pmm-server-2.12.3.tgz
fi
sleep 20

desc 'create PSMDB cluster'
kubectl_bin apply \
    -f $conf_dir/secrets.yml \
    -f $conf_dir/client.yml \
    -f $test_dir/conf/secrets.yml

apply_cluster $test_dir/conf/$cluster-rs0.yml
desc 'check if all 3 Pods started'
wait_for_running $cluster-rs0 3

# wait for prometheus
sleep 90
desc 'check if pmm-client container enabled'
compare_kubectl statefulset/$cluster-rs0
compare_kubectl service/$cluster-rs0
compare_kubectl statefulset/$cluster-cfg
compare_kubectl deployment/$cluster-mongos

desc 'check mongod metrics'
get_metric_values node_boot_time_seconds $namespace-$cluster-rs0-1 admin:admin
get_metric_values mongodb_connections $namespace-$cluster-rs0-1 admin:admin

#desc 'check mongo config  metrics'
get_metric_values node_boot_time_seconds $namespace-$cluster-cfg-1 admin:admin
get_metric_values mongodb_connections $namespace-$cluster-cfg-1 admin:admin

#desc 'check mongos metrics'
MONGOS_POD_NAME=$(kubectl get pod -l app.kubernetes.io/component=mongos -o jsonpath="{.items[0].metadata.name}")
get_metric_values node_boot_time_seconds $namespace-$MONGOS_POD_NAME admin:admin
#get_metric_values mongodb_mongos_connections ${cluster%%-rs0}-mongos-0

# wait for QAN
sleep 90

desc 'check QAN data'
get_qan20_values $cluster-rs0-0 admin:admin
get_qan20_values $cluster-cfg-0 admin:admin
get_qan20_values $MONGOS_POD_NAME admin:admin

if [[ -n "${OPENSHIFT}" ]]; then
    oc adm policy remove-scc-from-user privileged -z percona-server-mongodb-operator
fi

helm delete monitoring
destroy $namespace
